package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /**关注取关业务实现
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        // 1. 校验参数    authorApUserId   必须登录   operation 0  1
        if(dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确参数");
        }
        //判断关注类型
        Short operation = dto.getOperation();
        if(operation==null||(operation.intValue()!=0&&operation.intValue()!=1)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //判断是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if(apUser==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //不能自己关注自己
        //作者id
        Integer authorId = dto.getAuthorApUserId();
        //用户id
        Integer userId = apUser.getId();
        if(userId.equals(authorId)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"不能关注自己");
        }
        //判断是否已经关注  k:用户id  前面是关注列表集合名称    v: 作者id
        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorId));
        //如果分数不为空 且用户想要关注 则抛异常
        if(score!=null&&operation.intValue()==0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"您已关注过请勿重复关注");
        }
        //判断operation是0(关注) 还是 1(取关)
        if(operation.intValue()==0){
            //用户关注集合 添加字段  作者粉丝列表添加
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorId),System.currentTimeMillis());
            //作者粉丝列表增加
            redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST+authorId,String.valueOf(userId),System.currentTimeMillis());
        }else {
            //用户取关  关注列表中直接删除 作者id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST+userId,String.valueOf(authorId));
            //作者粉丝列表 直接删除用户id
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST+authorId,String.valueOf(userId));
        }

        return ResponseResult.okResult();
    }
}
